import useMappingProps from 't/common/hooks/useMappingProps';
import { usePropsTwoWayValues, zipFasDynamicFilter } from 't/common/utils';
import {
  computed,
  defineComponent,
  getCurrentInstance,
  nextTick,
  onMounted,
  reactive,
  ref,
  toRefs,
  watch,
} from 'vue';
import './index.scss';

import _ from 'lodash';

import { useQuasar } from '@teld/q-components';

// import { usePropsTwoWayValue } from 't/bussiness/utils';

import ChartConfig from './components/ChartConfig';
import ChartView from './components/ChartView';
import Tabs from './components/Tabs';

import TButton from 't/basic/button';
import TImportExport from 't/basic/import-export';
import TSelect from 't/basic/select';
import TDataGrid from 't/bussiness/data-grid';
import QBtn from '@teld/q-components/Button';
import QTabPanels, { QTabPanel } from '@teld/q-components/TabPanels';
import TBtnGroup from 't/basic/button-group';

import TQuickFilter from 't/bussiness/quick-filter';

import {
  propsSuffix,
  pickProps,
  mappingEvent,
} from 't/bussiness/mixed-view/utils';


import { mergeFilters, mergeFiltersBase } from 't/common/utils';


function mappingDataGridEvent(emit, emits) {
  return mappingEvent(emit, emits, '_GridData');
}

function pickDataGridProps(mappingProps) {
  return pickProps(mappingProps, 'gdBind', '_GridData');
}

/*
function propsSuffix(props, suffix) {
  if (!suffix) {
    return props;
  }

  return _.transform(
    props,
    (r, v, k) => {
      r[`${k}${suffix}`] = v;
    },
    {},
  );

  return returnValue;
}

function pickDataGridProps(mappingProps) {
  return pickProps(mappingProps, 'gdBind', '_GridData');
}

function pickProps(
  mappingProps,
  bindPropName = 'gdBind',
  suffix = '_GridData',
) {
  let withoutSuffixProps = _.transform(
    mappingProps,
    (r, propValue, propName) => {
      if (propName.endsWith(suffix)) {
        let withoutSuffix = propName.replace(suffix, '');
        if (false && attrs.hasOwnProperty(`v-model:${propName}`)) {
          r[`v-model:${withoutSuffix}`] = attrs[`v-model:${propName}`].value;
        } else {
          r[withoutSuffix] = propValue;
        }
      }
    },
    {},
  );

  let mergeProps = { ...mappingProps[bindPropName], ...withoutSuffixProps };

  let dynamicProps = {};
  Object.keys(mergeProps).forEach(key => {
    if (key.startsWith('v-model:')) {
      const p = key.replace('v-model:', '');
      dynamicProps[p] = mergeProps[key];
      dynamicProps[`onUpdate:${p}`] = e => emit(`update:${p}`, e);
    } else {
      if (false === mergeProps.hasOwnProperty(`v-model:${key}`)) {
        dynamicProps[key] = mergeProps[key];
      }
    }
  });

  return dynamicProps;
}

function mappingDataGridEvent(emit, emits) {
  return mappingEvent(emit, emits, '_GridData');
}
function mappingEvent(emit, emits, suffix) {
  let bindEvent = emits.map(eName => {
    return [
      `on${_.upperFirst(eName)}`,
      e => {
        console.log('mappingEvent', `${eName}${suffix}`);
        emit(`${eName}${suffix}`, e);
      },
    ];
  });

  bindEvent = Object.fromEntries(bindEvent);
  return bindEvent;
}
*/

export default defineComponent({
  name: 'TMixedView',
  directives: {
    removeTabindex: {
      mounted(el) {
        // 移除 tabindex 属性
        el?.removeAttribute('tabindex');
      },
    },
  },
  props: {
    curTab: {
      type: String,
      default() {
        return 'ListView';
      },
    },
    curTaba: {
      type: String,
      default() {
        return 'ListView';
      },
    },
    bbb: {
      type: String,
      default() {
        return 'ListView';
      },
    },
    optColumns: {
      type: [Array, String, Object],
      default() {
        return [];
      },
    },
    optDataSource: {
      type: [Array, String],
      default() {
        return [];
      },
    },
    ...propsSuffix(TDataGrid.props, '_GridData'),
    enableQuickFilter: {
      type: Boolean,
      default() {
        return false;
      },
    },
    ...propsSuffix(TQuickFilter.props, '_QuickFilter'),
    ...propsSuffix(TBtnGroup.props, '_ButtonGroup'),
    gdBind: {
      type: Object,
      default() {
        return {};
      },
    },
    advQueryWidget: {
      type: [Object, Boolean],
      default() {
        return false;
      },
    },
    isMock: Boolean,
    rows_all: {
      type: Array,
      default() {
        return [];
      },
    },
    loading_all: {
      type: Boolean,
      default() {
        return false;
      },
    },
    displayNameGridData: { type: String },
    displayChartView: { type: String },
    chartView: {
      type: Boolean,
      default() {
        return true;
      },
    },
    beforeExportJSScript: {
      type: String,
      default() {
        return '';
      },
    },
    listViewToolbarButtonGroups: {
      type: Boolean,
      default() {
        return false;
      },
    },
    chartFullHeight: {
      type: Number,
      default() {
        return 700;
      },
    },
    exportFileName: {
      type: String,
      default() {
        return '';
      },
    },
  },
  emits: [
    'update:bbb',
    'request',
    'request_all',
    'filterChanged',
    ...TDataGrid.emits.map(item => `${item}_GridData`),
    ...TQuickFilter.emits.map(item => `${item}_QuickFilter`),
    'toolbarClick',
    'listToolbarClick',
    // ...TBtnGroup.emits.map(item => `${item}_ButtonGroup`),
    'ListExport_BeforeExport',
    'ListExport_AfterExport',
  ],

  setup(props, { attrs, emit, expose, slots }) {
    try {
      const vm = getCurrentInstance();
      const $q = useQuasar();

      const Terms = {
        title: $q.lang.mixedView?.title,
        placeholder: $q.lang.mixedView?.placeholder,
        button: $q.lang.mixedView?.button,
        notify: $q.lang.mixedView?.notify,
      };

      const refComponent = ref();

      const { curTab: tab, ...twoWayProps } = usePropsTwoWayValues([
        'curTab',
        'curTaba',
        'AAA',
      ]);

      const tabsLoadedFlag = reactive({
        ListView: false,
        ChartView: false,
      });

      const resetTabLoadFlag = () => {
        tabsLoadedFlag.ListView = false;
        tabsLoadedFlag.ChartView = false;

        if (props.enableQuickFilter && refQuickFilter.value) {
          refQuickFilter.value.querySummary();
        }
      };

      let stopPageSizeWatching;

      //#region
      function debuggerAlert(msg) {
        // alert(msg)
        if (window.gDebugger || true) console.log('mixins_mixedView', msg);
      }

      function postChartInstanceApplys(targetID) {
        return TFF.common.ajax.getDataAsync({
          //@ts-ignore
          url: `${Funcs.FasRequestTagAdd(
            //@ts-ignore
            TFF.common.ajax.getServiceUrl('FASR-GetChartInstanceApplys'),
          )}`,
          type: 'post',
          data: {
            targetType: 0,
            targetID: targetID,
          },
        });
      }
      let lastChartInstanceApplysID = '';
      function getSchemeChartConfig(targetID = proxyThis?.Scheme?.ContentID) {
        // targetID = targetID || proxyThis?.Scheme?.ContentID;
        if (lastChartInstanceApplysID === targetID) {
          return Promise.resolve();
        }
        lastChartInstanceApplysID = targetID;
        return postChartInstanceApplys(targetID).then(res => {
          proxyThis.Scheme.Chart = {
            List: proxyThis.convertSchemeChartsConfig(res),
          };
          proxyThis.SetCharts();
          return Promise.resolve();
        });
      }

      function mockSchema() {
        return {
          ID: '4b57e6a7-600f-4e66-bbae-95f8f74db64e',
          PageID: 'c9985b2f-8a5c-42d9-bef9-4acfb190fbe4',
          DQID: '0a05dabd-fddb-448e-85a7-fcca21a78170',
          WarningID: '',
          Name: '00 待我处理',
          PlanRange: 1,
          IsSystem: false,
          IsDefault: true,
          IsAuth: true,
          UserID: 'a87e0bb9-15df-4cf9-8bf1-803a8ef71ea5',
          UserName: '张辰',
          SharedBy: '',
          ShareUsers: null,
          ContentID: 'ba83a3ac-e0ce-4568-828a-fc69f9939fb0',
          FilterContent:
            '{"ElementType":"Group","Filters":[{"ElementType":"Filter","Code":"SDO_DEP_BugState.Name","Condition":"notin","Value":"已关闭,已处理","Name":"状态","DataType":"String","ValueName":"已关闭,已处理","ValueType":0},{"ElementType":"Relation","Relation":"and"},{"ElementType":"Filter","Code":"DO_DEP_ProjectBug.AssignTo","Condition":"=","Value":"@我","Name":"指派给","DataType":"String","ValueName":"@我","ValueType":0}]}',
          FilterShow:
            '{"FilterModel":"Easy","FilterGroups":[{"ID":"362416b2-580f-a067-6491-975febec6c21","Type":"Filter","Relation":"and","Code":"SDO_DEP_BugState.Name","Name":"状态","Condition":"notin","Value":"已关闭,已处理","DataType":"String","ValueName":"已关闭,已处理","ValueType":0,"IsOff":false,"Children":[]},{"ID":"91d2038a-c06a-ee4b-896d-9b3860777234","Type":"Filter","Relation":"and","Code":"DO_DEP_ProjectBug.AssignTo","Name":"指派给","Condition":"=","Value":"@我","DataType":"String","ValueName":"@我","ValueType":0,"IsOff":false,"Children":[]}]}',
          ColumnContent: null,
          SortContent: null,
          CrossColumn: null,
          UseColumnContent: false,
          ListViewSet:
            '{"pageSize":50,"showAutoFilterRow":false,"displayColumns":[{"label":"单据编号","value":"Code"},{"label":"问题概述","value":"Name"}],"sortColumns":[]}',
          // '{"pageSize":50,"showAutoFilterRow":false,"displayColumns":[{"label":"单据编号","value":"Code"},{"label":"问题概述","value":"Name"},{"label":"状态","value":"SDO_DEP_BugState_Name"},{"label":"问题类别","value":"SDO_DEP_BugCategory_Name"},{"label":"严重级别","value":"SDO_DEP_Severity_Name"},{"label":"标记","value":"Tag"},{"label":"计划完成日期","value":"PlanFinishDate"},{"label":"所属团队","value":"DO_DEP_Teams_Name"},{"label":"验证人","value":"VerifyBy"},{"label":"创建时间","value":"CreateTime"}],"sortColumns":[]}',
          ChartViewSet: '{"ChartPageing":false}',
          PivotViewSet: '{"PivotPageing":false}',
          TreeViewSet: '{}',
          CardViewSet: '{}',
          PlanOrder: 115,
          TopTime: '0001-01-01 00:00:00',
          DefaultView: 0,
          Charts: [
            {
              ID: '3ebb2916-dff4-44fa-a1b2-363e5658c84a',
              ChartInstanceID: '4b99612e-5551-4321-b43b-a20a464277bd',
              ChartLib: null,
              Code: '按照 问题类别 统计',
              Name: '按照 问题类别 统计',
              ChartLibItemID: 'fas-pie-chart',
              DataSourceID: '',
              DemoData: '',
              ChartContent:
                '{"ChartName":"按照 问题类别 统计","ChartType":"fas-pie-chart","GroupColumn":"SDO_DEP_BugCategory_Name","Aggregation":"count","AggregationFiled":"","SortType":"value","DataSort":"","AggDateValue":"","visible":false}',
            },
          ],
          ValueJson: [
            [
              'SDO_DEP_BugState.Name',
              'notin',
              '{"value":"已关闭,已处理","name":"已关闭,已处理","valueType":0,"DataType":"String"}',
            ],
            'and',
            [
              'DO_DEP_ProjectBug.AssignTo',
              '=',
              '{"value":"@我","name":"@我","valueType":0,"DataType":"String"}',
            ],
          ],
          Content:
            '{"ElementType":"Group","Filters":[{"ElementType":"Filter","Code":"SDO_DEP_BugState.Name","Condition":"notin","Value":"已关闭,已处理","Name":"状态","DataType":"String","ValueName":"已关闭,已处理","ValueType":0},{"ElementType":"Relation","Relation":"and"},{"ElementType":"Filter","Code":"DO_DEP_ProjectBug.AssignTo","Condition":"=","Value":"@我","Name":"指派给","DataType":"String","ValueName":"@我","ValueType":0}]}',
        };
      }

      function switchView(viewName) {
        // if (false == props.chartView) {
        //   refChartView.value = 'ChartView' == viewName;
        // }
        if (false === refChartView.value) {
          viewName = 'ListView';
        }
        const oldValue = tabsLoadedFlag[viewName];
        tabsLoadedFlag[viewName] = true;
        tab.value = viewName;
        emit('update:curTab', viewName);
        if (oldValue == false) {
          console.log(
            'mixed-view',
            'switchView',
            viewName,
            props.rows_GridData.length,
            props.rows_all.length,
            chartRows.value.length,
          );
          // console.trace('mixed-view switchView')
          switch (viewName) {
            case 'ListView':
              if (props.enableQuickFilter) {
                setTimeout(() => {
                  refDataGrid?.value?.query();
                }, 100);
              } else {
                setTimeout(() => {
                  refDataGrid?.value?.query();
                });
              }
              break;
            case 'ChartView':
              // refChartView.value = true;
              getSchemeChartConfig().then(res => {
                queryChart();
              });
              break;
          }
        }
      }

      function queryChart() {
        // dynamicProps;
        // const { chartPaging, rowsPerPage, rowsNumber } = props.pagination;
        proxyThis.EnableChartPaging === 'yes'
          ? emit('request_GridData', {
              pagination: {
                page: mappingProps.pageIndex_GridData,
                rowsPerPage: mappingProps.pageSize_GridData,
              },
            })
          : emit('request_all');
      }

      const chartRows = computed(() => {
        return proxyThis.EnableChartPaging === 'yes'
          ? props.rows_GridData
          : props.rows_all;
      });

      const proxyThis = reactive({
        // dataGridInstance: computed(() => refDataGrid?.value),
        EnablePivotPaging: 'yes',
        EnableChartPaging: 'yes',
        schemeChanged: false,
        limitConf: { CheckCount: false },
        isSwitchTabs: false,
        SchemeVersion: 'v2',
        mappingConf: {
          ListView: {
            no: 0,
            Label: $q.lang.mixedView?.tabs?.ListView,
            Value: 'ListView',
          },
          TreeView: {
            no: 0,
            Label: $q.lang.mixedView?.tabs?.TreeView,
            Value: 'TreeView',
          },
          CardView: {
            no: 0,
            Label: $q.lang.mixedView?.tabs?.CardView,
            Value: 'CardView',
          },
          PivotView: {
            no: 1,
            Label: $q.lang.mixedView?.tabs?.PivotView,
            Value: 'PivotView',
          },
          ChartView: {
            no: 2,
            Label: $q.lang.mixedView?.tabs?.ChartView,
            Value: 'ChartView',
          },
        },
        GetUserProfile() {
          return {
            ListUserProfile: proxyThis.GetDataGridUserProfile(),
          };
        },
        GetCardGridScheme() {
          let cardGridInstance = proxyThis.getCardGridInstance();
          let cardGridConf = cardGridInstance
            ? cardGridInstance.GetScheme()
            : proxyThis.Scheme.CardGrid;
          return cardGridConf;
        },
        GetDataGridScheme() {
          let dataGridInstance = proxyThis.getDataGridInstance();
          let dataGridConf = dataGridInstance
            ? dataGridInstance.GetScheme()
            : proxyThis.Scheme.DataGrid;
          return dataGridConf;
        },
        GetDataGridUserProfile() {
          let dataGridInstance = proxyThis.getDataGridInstance();
          let dataGridConf = dataGridInstance
            ? dataGridInstance.GetUserProfile()
            : {};
          return dataGridConf;
        },
        GetTreeGridScheme() {
          let treeGridInstance = proxyThis.getTreeGridInstance();
          let treeGridConf = treeGridInstance
            ? treeGridInstance.GetScheme()
            : proxyThis.Scheme.TreeGrid;
          return treeGridConf;
        },
        GetPivotGridScheme() {
          let pivotGridInstance = proxyThis.getPivotGridInstance();
          let pivotConf =
            pivotGridInstance && pivotGridInstance.getSchema
              ? { Scheme: pivotGridInstance.getSchema() }
              : proxyThis.Scheme.Pivot || { Scheme: [] };
          return pivotConf;
        },
        GetChartGridScheme() {
          return { List: chartList.value };
        },
        GetScheme(version) {
          let dataGridScheme = proxyThis.GetDataGridScheme();
          let cardGridScheme = proxyThis.GetCardGridScheme();
          let treeGridScheme = proxyThis.GetTreeGridScheme();

          let pivotGridScheme = proxyThis.GetPivotGridScheme();

          let chartGridScheme = proxyThis.GetChartGridScheme();

          let scheme = {
            DefaultView: tab.value,
            DataGrid: dataGridScheme,
            CardGrid: cardGridScheme,
            TreeGrid: treeGridScheme,
            Pivot: pivotGridScheme,
            Chart: chartGridScheme,
            PivotPageing: proxyThis.EnablePivotPaging == 'yes',
            ChartPageing: proxyThis.EnableChartPaging == 'yes',
          };

          version = version || proxyThis.SchemeVersion;
          let getScheme_func =
            this[`GetScheme_${version}`] || proxyThis.GetScheme_v2;
          let postScheme = getScheme_func(scheme);
          console.log('mixed-view', 'GetScheme', postScheme);
          if (proxyThis.Scheme?.Chart?.List) {
            // proxyThis.Scheme.Chart.List = postScheme.Charts;
            proxyThis.Scheme.Chart.List = proxyThis.convertSchemeChartsConfig(
              postScheme.Charts,
            );
          }
          return postScheme;
        },

        GetScheme_v1(scheme) {
          let postScheme = {
            PivotPageing: scheme.PivotPageing,
            ChartPageing: scheme.ChartPageing,
            UseColumnContent: true,
            DefaultView: (
              proxyThis.mappingConf[scheme.DefaultView] || { no: '' }
            ).no,
            ColumnContent: JSON.stringify(scheme.DataGrid.displayColumns),
            SortContent: JSON.stringify(scheme.DataGrid.sortColumns),
            CrossColumn: JSON.stringify(scheme.Pivot.Scheme),
            Charts: _.map(scheme.Chart.List, chartConf => {
              let item = _.cloneDeep(chartConf);

              let returnValue = {};

              if (item._chart) {
                returnValue = item._chart;
                delete item._chart;
              }

              returnValue.Code = item.ChartName;
              returnValue.Name = item.ChartName;
              returnValue.ChartLibItemID = item.ChartType;
              returnValue.ChartContent = JSON.stringify(item);

              return returnValue;
            }),
          };

          return postScheme;
        },

        GetScheme_v2(scheme) {
          let postScheme = {
            ListViewSet: JSON.stringify(scheme.DataGrid),
            CardViewSet: JSON.stringify(scheme.CardGrid),
            TreeViewSet: JSON.stringify(scheme.TreeGrid),
            ChartViewSet: JSON.stringify({ ChartPageing: scheme.ChartPageing }),
            PivotViewSet: JSON.stringify({
              PivotPageing: scheme.PivotPageing,
              Scheme: scheme.Pivot.Scheme,
            }),
            UseColumnContent: true,
            DefaultView: (
              proxyThis.mappingConf[scheme.DefaultView] || { no: '' }
            ).no,
            Charts: _.map(scheme.Chart.List, chartConf => {
              let item = _.cloneDeep(chartConf);

              let returnValue = {};

              if (item._chart) {
                returnValue = item._chart;
                delete item._chart;
              }

              returnValue.Code = item.ChartName;
              returnValue.Name = item.ChartName;
              returnValue.ChartLibItemID = item.ChartType;
              returnValue.ChartContent = JSON.stringify(item);

              return returnValue;
            }),
          };

          return postScheme;
        },
        ChangeView: switchView,
        advQueryWidget: computed(
          () => mockAdvQueryWidget.value || props.advQueryWidget,
        ),
        SetScheme(scheme, userProfile, version) {
          if (props.isMock) scheme = mockSchema();
          proxyThis.schemeChanged = true;
          if (proxyThis.limitConf.CheckCount && proxyThis.isSwitchTabs) {
            proxyThis.schemeChanged = false;
          }
          debuggerAlert('SetScheme');
          proxyThis.SchemeVersion =
            version || _.has(scheme, 'ListViewSet') ? 'v2' : 'v1';
          // if (proxyThis.SchemeVersion == 'v1') {
          //   Funcs.Notify(Terms.notify.notError, Terms.notify.version, 'warning');
          // }
          let setScheme_func =
            proxyThis[`SetScheme_${proxyThis.SchemeVersion}`] ||
            proxyThis.SetScheme_v2;
          setScheme_func(scheme, userProfile);

          proxyThis.SetScheme_Exec();
        },
        SetScheme_v1(scheme, userProfile) {
          debuggerAlert('setScheme_v1');

          let schemeChartsConf = {
            List: proxyThis.convertSchemeChartsConfig(scheme.Charts),
          };
          if (scheme.ID !== proxyThis.SchemeID) {
            lastChartInstanceApplysID = '';
          } else {
            schemeChartsConf.List = proxyThis.Scheme?.Chart?.List || [];
          }
          proxyThis.SchemeID = scheme.ID;

          proxyThis.Scheme = {
            ContentID: scheme.ContentID,
            PivotPageing: scheme.PivotPageing,
            ChartPageing: scheme.ChartPageing,
            DefaultView: (
              _.find(proxyThis.mappingConf, { no: scheme.DefaultView }) || {
                Value: '',
              }
            ).Value,
            DataGrid: {
              displayColumns: JSON.parse(scheme.ColumnContent),
              sortColumns: JSON.parse(scheme.SortContent),
            },
            Pivot: {
              Scheme: JSON.parse(scheme.CrossColumn) || [],
            },
            Chart: schemeChartsConf,
          };

          return proxyThis.Scheme;
        },
        convertSchemeChartsConfig(charts) {
          return (
            _.map(charts, chart => {
              let chartConf = JSON.parse(chart.ChartContent);
              chartConf._chart = chart;
              return chartConf;
            }) || []
          );
        },
        SetScheme_v2(scheme, userProfile) {
          scheme = _.cloneDeep(scheme);
          scheme.ChartViewSet = JSON.parse(scheme.ChartViewSet || '{}');
          scheme.ListViewSet = JSON.parse(scheme.ListViewSet || '{}');
          scheme.CardViewSet = JSON.parse(scheme.CardViewSet || '{}');
          scheme.TreeViewSet = JSON.parse(scheme.TreeViewSet || '{}');
          scheme.PivotViewSet = JSON.parse(scheme.PivotViewSet || '{}');
          userProfile = JSON.parse(userProfile || '{}');

          if (proxyThis.limitConf.CheckCount && proxyThis.Scheme.DataGrid) {
            let newDC = JSON.stringify(scheme.ListViewSet.displayColumns);
            let oldDC = JSON.stringify(
              proxyThis.Scheme.DataGrid.displayColumns,
            );

            let newSC = JSON.stringify(scheme.ListViewSet.sortColumns);
            let oldSC = JSON.stringify(proxyThis.Scheme.DataGrid.sortColumns);

            if (proxyThis.isSwitchTabs) {
              if (newDC == oldDC && newSC != oldSC) {
                proxyThis.schemeChanged = false;
              }
              if (proxyThis.SchemeID != scheme.ID) {
                proxyThis.schemeChanged = true;
              }
            } else {
              if (proxyThis.SchemeID == scheme.ID && newSC != oldSC) {
                proxyThis.schemeChanged = false;
              } else if (proxyThis.SchemeID == scheme.ID) {
                proxyThis.schemeChanged = false;
              }
            }
          }
          let schemeChartsConf = {
            List: proxyThis.convertSchemeChartsConfig(scheme.Charts),
          };
          if (scheme.ID !== proxyThis.SchemeID) {
            lastChartInstanceApplysID = '';
          } else {
            schemeChartsConf.List = proxyThis.Scheme?.Chart?.List || [];
          }
          proxyThis.SchemeID = scheme.ID;

          proxyThis.Scheme = {
            ContentID: scheme.ContentID,
            DataGridUserProfile: userProfile || {},
            PivotPageing: scheme.PivotViewSet.PivotPageing,
            ChartPageing: scheme.ChartViewSet.ChartPageing,
            DefaultView: (
              _.find(proxyThis.mappingConf, { no: scheme.DefaultView }) || {
                Value: '',
              }
            ).Value,
            DataGrid: scheme.ListViewSet,
            CardGrid: scheme.CardViewSet,
            TreeGrid: scheme.TreeViewSet,
            Pivot: scheme.PivotViewSet,
            Chart: schemeChartsConf,
          };
          return proxyThis.Scheme;
        },
        SetScheme_Exec() {
          if (_.isNil(proxyThis.advQueryWidget)) return;

          debuggerAlert('setScheme_Exec');

          proxyThis.TabLoaded = {};

          let {
            DataGrid: dataGridConf,
            CardGrid: cardGridConf,
            TreeGrid: treeGridConf,
            Pivot: pivotConf,
            Chart: chartConf,
            DataGridUserProfile: dataGridUserProfileConf,
          } = proxyThis.Scheme;
          console.log(
            'mixed-view',
            'SetScheme_Exec DefaultView',
            proxyThis.Scheme.DefaultView,
            !!proxyThis.Scheme.DefaultView,
          );
          if (proxyThis.Scheme.DefaultView) {
            // if (
            //   proxyThis.Scheme.DefaultView ==
            //     proxyThis.mappingConf.PivotView.Value &&
            //   true !== proxyThis.options.statisticalView
            // ) {
            //   proxyThis.Scheme.DefaultView = proxyThis.mappingConf.ListView.Value;
            // }

            // if (
            //   proxyThis.Scheme.DefaultView ==
            //     proxyThis.mappingConf.ChartView.Value &&
            //   true !== proxyThis.options.ChartView
            // ) {
            //   proxyThis.Scheme.DefaultView = proxyThis.mappingConf.ListView.Value;
            // }

            proxyThis.ChangeView(proxyThis.Scheme.DefaultView);
            // _.debounce(
            //   proxyThis.SetSwitchTabsActive,
            //   1000,
            // )(proxyThis.Scheme.DefaultView);
            // proxyThis.ActiveViewBase(proxyThis.Scheme.DefaultView);
            // proxyThis.SetSwitchTabsActive(proxyThis.Scheme.DefaultView);
          }

          if (dataGridConf) {
            mappingProps.pageSize_GridData =
              dataGridConf.pageSize || mappingProps.pageSize_GridData;
            let dataGridInstance = proxyThis.getDataGridInstance();
            if (dataGridInstance) {
              let userProfile = dataGridUserProfileConf;
              dataGridInstance.SetScheme(dataGridConf, userProfile);
            }
          }

          if (cardGridConf) {
            let cardGridInstance = proxyThis.getCardGridInstance();
            if (cardGridInstance) {
              let cardGridColumns = _.cloneDeep(proxyThis.options.columns);
              if (
                !proxyThis.isDevEnv &&
                cardGridInstance.options.selectMode == 'multiple' &&
                _.size(proxyThis.Scheme.CardGrid.displayColumns) > 0
              ) {
                _.each(cardGridColumns, col => {
                  col.isShow = false;
                });
              }
              cardGridInstance.options.columns = cardGridColumns;
              cardGridInstance.SetScheme(cardGridConf);
            }
          }

          if (treeGridConf) {
            let treeGridInstance = proxyThis.getTreeGridInstance();
            if (treeGridInstance) {
              let treeGridColumns = _.cloneDeep(proxyThis.options.columns);
              if (
                !proxyThis.isDevEnv &&
                treeGridInstance.options.selectMode == 'multiple' &&
                _.size(proxyThis.Scheme.TreeGrid.displayColumns) > 0
              ) {
                _.each(treeGridColumns, col => {
                  col.isShow = false;
                });
              }
              treeGridInstance.options.columns = treeGridColumns;
              treeGridInstance.SetScheme(treeGridConf);
            }
          }

          proxyThis.EnablePivotPaging = proxyThis.Scheme.PivotPageing
            ? 'yes'
            : 'no';
          proxyThis.EnableChartPaging = proxyThis.Scheme.ChartPageing
            ? 'yes'
            : 'no';

          if (pivotConf) {
            proxyThis.SetPivotScheme();
          }

          if (chartConf && chartConf.List) {
            proxyThis.SetCharts();
          }

          let pivotPagingInstance =
            proxyThis.getPivotPagingDropDownBoxInstance();
          let chartPagingInstance =
            proxyThis.getChartPagingDropDownBoxInstance();
          if (pivotPagingInstance) {
            // pivotPagingInstance.widget._Events = pivotPagingInstance.widget.Events;
            pivotPagingInstance.widget.Events = [];
            pivotPagingInstance.Value = proxyThis.EnablePivotPaging;
            setTimeout(() => {
              pivotPagingInstance.widget.Events =
                pivotPagingInstance.widget._Events;
            }, 500);
          }
          if (chartPagingInstance) {
            chartPagingInstance.widget.Events = [];
            chartPagingInstance.Value = proxyThis.EnableChartPaging;
            setTimeout(() => {
              chartPagingInstance.widget.Events =
                chartPagingInstance.widget._Events;
            }, 500);
          }

          let isAutoQuery =
            proxyThis.Scheme.DefaultView !=
            proxyThis.mappingConf.ListView.Value;
          console.log('MixedView setScheme isAutoQuery', isAutoQuery);
          return isAutoQuery;
        },
        getDataGridInstance: () => refDataGrid?.value,
        getCardGridInstance: () => null,
        getTreeGridInstance: () => null,
        getChartGridInstance: () => refChartGrid?.value,
        getPivotGridInstance: () => null,
        getPivotPagingDropDownBoxInstance: () => null,
        getChartPagingDropDownBoxInstance: () => null,
        options: { columns: props.optColumns },
        Scheme: {},
        SetCharts() {
          chartList.value = (proxyThis.Scheme.Chart || { List: [] }).List;
        },
        SetPivotScheme() {
          let pivotGridInstance = proxyThis.getPivotGridInstance();
          if (pivotGridInstance && pivotGridInstance.setSchema) {
            let pivotColumns = _.get(proxyThis.Scheme, 'Pivot.Scheme', []);
            if (pivotColumns && _.size(pivotColumns) == 0) {
              let cloneColumns = _.cloneDeep(proxyThis.options.columns);
              pivotColumns = proxyThis.columns2PivotColumns(cloneColumns);
            }

            if (pivotColumns && pivotColumns.forEach) {
              let colMap = _.transform(
                proxyThis.options.columns,
                (r, col) => {
                  r[col.dataField] = col.caption;
                },
                {},
              );
              pivotColumns.forEach(col => {
                if (colMap[col.dataField]) {
                  col.caption = colMap[col.dataField];
                }
              });
            }
            pivotGridInstance.setSchema(pivotColumns);
          }
        },
        UpdateAdvQuery(msg, execQuery = true) {
          if (proxyThis.advQueryWidget) {
            debuggerAlert('mixinsView.UpdateAdvQuery ' + msg);
            // let execQuery = false;
            // if (proxyThis.DataGridInstance) {
            //   execQuery = proxyThis.DataGridInstance.updateAdvQueryFlagExecQuery;
            // }
            // if (proxyThis.CardGridInstance) {
            //   execQuery = proxyThis.CardGridInstance.updateAdvQueryFlagExecQuery;
            // }
            // if (proxyThis.TreeGridInstance) {
            //   execQuery = proxyThis.TreeGridInstance.updateAdvQueryFlagExecQuery;
            // }
            proxyThis.advQueryWidget.updateAdvQuery(null, null, execQuery);
            // if (proxyThis.DataGridInstance) {
            //   proxyThis.DataGridInstance.updateAdvQueryFlagExecQuery = false;
            // }
            // if (proxyThis.CardGridInstance) {
            //   proxyThis.CardGridInstance.updateAdvQueryFlagExecQuery = false;
            // }
            // if (proxyThis.TreeGridInstance) {
            //   proxyThis.TreeGridInstance.updateAdvQueryFlagExecQuery = false;
            // }
          }
        },
        UpdateAdvQueryWithUserProfile(msg, userProfile) {
          if (
            proxyThis.advQueryWidget &&
            proxyThis.advQueryWidget.setUserProfileByMixView
          ) {
            debuggerAlert('mixinsView.UpdateAdvQueryWithUserProfile ' + msg);
            proxyThis.advQueryWidget.setUserProfileByMixView(userProfile);
          }
        },
        UpdateAdvQueryWithResetSort(msg, userProfile) {
          if (
            proxyThis.advQueryWidget &&
            proxyThis.advQueryWidget.setUserProfileByMixView
          ) {
            debuggerAlert('mixinsView.UpdateAdvQueryWithResetSort ' + msg);
            proxyThis.advQueryWidget
              .setUserProfileByMixView(userProfile)
              .then(() => {
                proxyThis.advQueryWidget.resetMixViewSort();
              });
          }
        },
      });

      let sUserProfile = '';
      const OnUpdateAdvQueryWithUserProfile = () => {
        if (proxyThis.advQueryWidget) {
          var userProfile = proxyThis.GetDataGridUserProfile();
          var userProfileJSON = JSON.stringify(userProfile);
          if (sUserProfile != userProfileJSON) {
            sUserProfile = userProfileJSON;
            proxyThis.UpdateAdvQueryWithUserProfile(
              'OnUpdateAdvQueryWithUserProfile',
              userProfile,
            );
          }
        }
      };

      const OnUpdateAdvQueryWithResetSort = () => {
        if (proxyThis.advQueryWidget) {
          var userProfile = proxyThis.GetDataGridUserProfile();
          proxyThis.UpdateAdvQueryWithResetSort(
            'OnUpdateAdvQueryWithResetSort',
            userProfile,
          );
        }
      };

      const OnUpdateAdvQueryWithPageSizeChange = () => {
        if (proxyThis.advQueryWidget) {
          proxyThis.UpdateAdvQuery('dataGridPageSizeChange', false);
        }
      };
      //#endregion

      const filterExpressionFromAdvQueryWidget = computed(() => {
        let filterExpression = proxyThis.advQueryWidget
          ? proxyThis.advQueryWidget.filterExpression || null
          : null;
        return filterExpression;
      });

      const filterExpressionBase = computed(() => {
        let filterExpression = filterExpressionFromAdvQueryWidget.value;

        if (props.enableQuickFilter) {
          let quickFilterExpression =
            refQuickFilter.value?.getQuickFilter(filterExpression);
          if (
            quickFilterExpression &&
            quickFilterExpression.Filters &&
            quickFilterExpression.Filters.length > 0
          ) {
            filterExpression = JSON.stringify(quickFilterExpression);
          }
        }

        _.each(refExternalQuickFilter.value || [], qf => {
          if (qf && qf.getFilters) {
            filterExpression = qf.getFilters(filterExpression);
          }
        });

        return filterExpression;
      });

      const filterExpression = computed(() => {
        let filterExpression = filterExpressionBase.value;

        if (props.enableGrouping_GridData && refDataGrid.value?.quickGroup) {
          filterExpression =
            refDataGrid.value.quickGroup.getFilters(filterExpression);
        }
        return filterExpression;
      });

      const groupByFilterExpression = computed(() => {
        let filterExpression = refDataGrid.value.quickGroup.getGroupByFilter(
          filterExpressionBase.value,
        );
        return filterExpression;
      });

      const sortExpression = computed(() => {
        return proxyThis.advQueryWidget
          ? proxyThis.advQueryWidget.sortExpression || null
          : null;
      });
      const mockAdvQueryWidget = ref(null);

      const publicMethod = {
        setSchemeWithUserProfile(userProfile, plan = { ListViewSet: '' }) {
          sUserProfile = userProfile;
          proxyThis.Scheme.DataGridUserProfile = JSON.parse(
            userProfile || '{}',
          );

          let planListViewSet = JSON.parse(plan.ListViewSet);
          proxyThis.Scheme.DataGrid = {
            displayColumns: planListViewSet.displayColumns || [],
            sortColumns: planListViewSet.sortColumns || [],
          };
          let dataGridInstance = proxyThis.getDataGridInstance();
          if (dataGridInstance) {
            let {
              DataGrid: dataGridConf,
              DataGridUserProfile: dgUserProfile,
            } = proxyThis.Scheme;
            dataGridInstance.SetScheme(dataGridConf, dgUserProfile);
          }
        },
        setScheme(scheme, userProfile, version) {
          if (
            props.enableQuickFilter &&
            refQuickFilter.value &&
            refQuickFilter.value.clearSelected
          ) {
            if (proxyThis.SchemeID != scheme.ID) {
              refQuickFilter.value.clearSelected();
            }
          }
          resetTabLoadFlag();
          console.log('mixed-view', 'publicMethod.setScheme');
          // console.trace("mixed-view publicMethod.setScheme", scheme, userProfile)
          sUserProfile = userProfile;
          proxyThis.SetScheme(scheme, userProfile, version);
        },
        getScheme() {
          return proxyThis.GetScheme();
        },
        switchView: switchView,
        query() {
          console.log('mixed-view', 'query');
          resetTabLoadFlag();
          publicMethod.switchView(tab.value);
        },
        refreshHeight() {
          refDataGrid.value?.refreshHeight();
        },
        refreshByData(data) {},
        filterExpression: filterExpression,
        groupByFilterExpression: groupByFilterExpression,
        sortExpression: sortExpression,
        fasPageIndex: computed(() => {
          return refDataGrid?.value.pageIndex;
        }),
        fasPageCount: computed(() => {
          return refDataGrid?.value.pageSize;
        }),

        /** QuickFilter PublicMethod */
        getGroupByFilter(advancedFilter) {
          if (refQuickFilter.value?.getGroupByFilter) {
            return refQuickFilter.value?.getGroupByFilter(
              advancedFilter || filterExpressionFromAdvQueryWidget.value,
            );
          }
          return advancedFilter;
        },
        wrapSummary: (quickItemSummaryRaw, Cnt) => {
          return refQuickFilter.value?.wrapSummary(quickItemSummaryRaw, Cnt);
        },
        getSummaryFields: () => {
          return refQuickFilter.value?.getSummaryFields();
        },
        quickFilterSelectedValue: function (args) {
          return refQuickFilter.value.getSelectedValue(args);
        },
        fasDynamicFilter: computed(() => {
          let v = refQuickFilter.value
            ? refQuickFilter.value.getFasDynamicFilter(filterExpression.value)
            : zipFasDynamicFilter({}, filterExpression.value);
          console.log('fasDynamicFilter', v);
          return v;
        }),
        fasDynamicSort: computed(() => {
          let returnValue = [];
          let s = sortExpression.value;
          if (s) {
            const sortExpression = JSON.parse(s);
            returnValue = sortExpression.map(v => {
              return { FieldName: v.SortColumn, SortType: v.SortType };
            });
          }
          return returnValue;
        }),
        //GroupByFilterWithAction
        getSummaryFilter(advancedFilter = null) {
          return refQuickFilter.value?.zipFasDynamicFilter(
            {},
            JSON.parse(publicMethod.getGroupByFilter(advancedFilter)).Filters,
          );
        },
        getQuickGroupSummaryFilter(advancedFilter = null) {
          return {
            ...zipFasDynamicFilter(
              {},
              filterExpressionFromAdvQueryWidget.value,
            ),
            ...(refQuickFilter.value?.getFasDynamicFilter() || {}),
            ...publicMethod.getSummaryFilter(advancedFilter),
          };
        },
        getQuickGroupSummaryFields() {
          return refDataGrid.value?.quickGroup?.getSummaryFields() || '';
        },
        setFilters(filters) {
          return refQuickFilter.value?.setFilters(filters);
        },
        getFilters(filters) {
          return refQuickFilter.value?.getFilters(filters);
        },
        mergeFiltersBase(target = {}, ...sArgs) {
          return mergeFiltersBase(target, ...sArgs);
        },
        mergeFilters(target = {}, ...sArgs) {
          return mergeFilters(target, ...sArgs);
        },
        registerQuickFilter(quickFilter) {
          if (quickFilter && quickFilter.getFilters) {
            if (!_.find(refExternalQuickFilter.value, quickFilter)) {
              refExternalQuickFilter.value.push(quickFilter);
            }
          }
          return this;
        },
        unregisterQuickFilter(quickFilter) {
          _.remove(refExternalQuickFilter.value, quickFilter);
          return this;
        },
        clearQuickFilter() {
          refExternalQuickFilter.value = [];
          return this;
        },
        setSelectedItem(obj) {
          return refQuickFilter.value?.setSelectedItem(obj);
        },
        updateByFilter(w) {
          return refQuickFilter.value?.updateByFilter(w);
        },
        /** QuickFilter PublicMethod */
        export2(type = 'all') {
          //export2是为了兼容导出组件的限制
          return refImportExport.value?.export2(type);
        },
        export(type = 'all') {
          return refImportExport.value?.export2(type);
        },
        exportInstance: computed(() => {
          return refImportExport.value;
        }),
        registerAdvQueryWidget(aqWidget) {
          mockAdvQueryWidget.value = aqWidget;
        },
        setExportConfigMore(config) {
          if (config) {
            let { AdvancedFilter, AdvancedSort } = config;
            if (AdvancedFilter == null && AdvancedSort == null) {
              publicMethod.registerAdvQueryWidget(null);
            } else {
              publicMethod.registerAdvQueryWidget({
                filterExpression: AdvancedFilter,
                sortExpression: AdvancedSort,
              });
            }
          } else {
            publicMethod.registerAdvQueryWidget(null);
          }
        },
      };

      const refExternalQuickFilter = ref([]);

      const C_TOOLBAR_KEY = {
        lvGroupfilter: 'lvGroupfilter',
        lvFilter: 'lvFilter',
        lvColumnsetting: 'lvColumnsetting',
        lvExport: 'lvExport',
        lvExportlist: 'lvExportlist',
      };

      const toolbarMethod = {
        C_TOOLBAR_KEY,
        gridToolbarInstance: computed(() => refListViewToolbarGroup?.value),
        setToolbarVisibleByCode(code, value) {
          toolbarMethod.gridToolbarInstance.value?.setVisibleByCode(
            code,
            value,
          );
        },

        setToolbarVisible(p) {
          for (let k in p) {
            toolbarMethod.setToolbarVisibleByCode(k, p[k]);
          }
        },

        toolbarByGroupMapping: computed(() =>
          _.groupBy(mappingProps.staticItems_ButtonGroup, 'groupCode'),
        ),
        setToolbarVisibleByGroups(g) {
          debugger;
          for (let k in g) {
            toolbarMethod.toolbarByGroupMapping.value[k]?.forEach(v => {
              toolbarMethod.setToolbarVisibleByCode(v.code, g[k]);
            });
          }
        },
      };

      const [mappingProps, mappingExpose] = useMappingProps(props, {
        curTab: tab,
        ...twoWayProps,
        dataGridInstance: computed(() => refDataGrid?.value),
        treeGridInstance: null,
        cardGridInstance: null,
        gridInstance: computed(() => getGridInstance()),
        quickFilterGridInstance: computed(() => refQuickFilter?.value),
        ...publicMethod,
        ...toolbarMethod,
      });

      onMounted(() => {
        nextTick(() => {
          console.log('props.advQueryWidget', props.advQueryWidget);
          if (!props.advQueryWidget) {
            resetTabLoadFlag();
            if (props.optDataSource instanceof Object) {
              if (false == props.optDataSource.LoadDataTime) {
                publicMethod.query();
              }
            }
          }
        });
      });

      const getGridInstance = () => {
        switch (tab.value) {
          case 'ListView':
            return refDataGrid?.value;
            break;

          case 'ChartView':
            return refDataGrid?.value;
            break;

          default:
            refDataGrid?.value;
            break;
        }
      };

      const $lang = $q.lang.mixedView || {};

      const refChartView = ref(props.chartView);

      const tabs = computed(() => {
        let displayName = {
          ListView: props.displayNameGridData,
          ChartView: props.displayChartView,
        };

        let tabsLang = {
          ListView: '列表视图',
          ChartView: '图表视图',
          ...$lang?.tabs,
        };

        let returnValue = Object.keys(tabsLang).map(key => {
          return {
            label: displayName[key] || tabsLang[key],
            code: key,
          };
        });

        if (false === refChartView.value) {
          _.remove(returnValue, { code: 'ChartView' });
        }
        return returnValue;
      });

      expose(mappingExpose);

      const renderTabs = () => {
        return (
          <Tabs
            v-model={tab.value}
            onUpdate:modelValue={val => {
              publicMethod.switchView(val);
            }}
            items={tabs.value}
          ></Tabs>
        );
      };

      const refDataGrid = ref();
      const refChartGrid = ref();
      const dataGridGroupFilterClickHandler = () => {
        debugger;
        refDataGrid.value.isGrouping = !refDataGrid.value.isGrouping;
        // proxyThis.UpdateAdvQuery('dataGridFilterClickHandler', false);
      };
      const dataGridFilterClickHandler = () => {
        debugger;
        refDataGrid.value.showAutoFilterRow =
          !refDataGrid.value.showAutoFilterRow;
        proxyThis.UpdateAdvQuery('dataGridFilterClickHandler', false);
      };

      const exportConfig = computed(() => {
        let dgVisibleColumns = refDataGrid.value?.getVisibleColumns();

        let Columns = _.map(mappingProps.optColumns, col => {
          let mapping = [];
          if (
            col.enumDisp &&
            col.enumDisp.valMapping &&
            col.enumDisp.enumRanges
          ) {
            mapping = _.map(col.enumDisp.enumRanges, item => {
              return {
                text: item.text,
                val: item.val,
                valueReferenceExpr: item.ValueInfo_text,
              };
            });
          }

          let isShow = dgVisibleColumns?.includes(col.dataField);
          let showIndex = isShow
            ? dgVisibleColumns.indexOf(col.dataField)
            : 9999;
          return {
            isShow: isShow,
            showIndex: showIndex,
            ColName: col.dataField,
            DataType: col.dataType,
            ExcelColName: col.caption,
            ValueInfo_ExcelColName: col.ValueInfo_caption,
            Format: col.dataFormat || {},
            Mapping: mapping,
          };
        });

        Columns = _.sortBy(Columns, 'showIndex');

        return {
          // DataSource: {
          //   ActionID: "ActionID"
          // },
          DataSource: {
            ActionID: props.optDataSource.DataSource,
            ActionCode: props.optDataSource.DataBind,
            Parameters: _.map(props.optDataSource.Parameters, p => {
              let pValue = p.Value;
              return {
                ParameterName: p.Code,
                ParameterValue: pValue,
              };
            }),
            ActionType: props.optDataSource.ActionType,
            ExportType: 0,
          },
          Columns: Columns,
        };
        // return props.optColumns;
        // return {
        //   "ID": "9bcc5a37-ea15-23e4-156a-88de2d41d2ba", "Code": "ExportConfig", "Name": "导出高级设置", "IsReadOnly": false, "IsEnum": false, "IsRef": true, "IsInternational": true, "NeedSpecialTreatment": true, "ValueType": "String", "Description": "导出高级设置", "PropertyEditor": { "PropertyEditorType": 26, "ConfigJSON": { "columnsDefine": { "ColName": { "noedit": true, "Type": "String", "mockValue": "字段名称" }, "ExcelColName": { "noedit": false, "Type": "String", "mockValue": "Excel列名称" }, "isShow": { "PropType": 0, "default": true, "Type": "Bool", "mockValue": "是否导出" } } }, "Extends": {} }, "DefaultValue": "", "IsRequired": false, "PropType": 1, "Level": 0, "ParentID": "", "ShowValue": "", "MappingName_PC": "", "MappingName_Mobile": "", "IsNative": true, "FasDefaultValue": "", "Value": "", "DisplayName": "", "hide": false, "ExportPageSize": 1000, "DataSource": { "ActionID": "14e3f3f4-3e89-4b73-a7ec-bd3610168ec7", "ActionCode": "GetCDO_DO_export_zhangbao1BasicList", "Parameters": [{ "ParamType": 0, "ParameterName": "DefaultInputFilter", "ParameterValue": null }, { "ParamType": 0, "ParameterName": "PageIndex", "ParameterValue": null }, { "ParamType": 0, "ParameterName": "PageSize", "ParameterValue": null }, { "ParamType": 0, "ParameterName": "AdvancedFilter", "ParameterValue": null }, { "ParamType": 0, "ParameterName": "AdvancedSort", "ParameterValue": null }], "ActionType": 3, "ExportType": 0 },
        //   "Columns": [
        //     { "isShow": false, "ColName": "ID", "ExcelColName": "主键ID", "DataType": "String", "ValueInfo_ColName": { "ShowValue": "ID", "ReferenceExpr": "Schema.DQ.GetCDO_DO_export_zhangbao1BasicList.Sources.DO_export_zhangbao1.Columns.ID.Code", "Type": 0 }, "ValueInfo_ExcelColName": { "ShowValue": "主键ID", "ReferenceExpr": "Schema.DQ.GetCDO_DO_export_zhangbao1BasicList.Sources.DO_export_zhangbao1.Columns.ID.Text", "Type": 0 } },
        //     { "isShow": true, "ColName": "Code", "ExcelColName": "编号", "DataType": "String", "ValueInfo_ColName": { "ShowValue": "Code", "ReferenceExpr": "Schema.DQ.GetCDO_DO_export_zhangbao1BasicList.Sources.DO_export_zhangbao1.Columns.Code.Code", "Type": 0 }, "ValueInfo_ExcelColName": { "ShowValue": "编号", "ReferenceExpr": "Schema.DQ.GetCDO_DO_export_zhangbao1BasicList.Sources.DO_export_zhangbao1.Columns.Code.Text", "Type": 0 } },
        //     { "isShow": false, "ColName": "Name", "ExcelColName": "名称", "DataType": "String", "ValueInfo_ColName": { "ShowValue": "Name", "ReferenceExpr": "Schema.DQ.GetCDO_DO_export_zhangbao1BasicList.Sources.DO_export_zhangbao1.Columns.Name.Code", "Type": 0 }, "ValueInfo_ExcelColName": { "ShowValue": "名称", "ReferenceExpr": "Schema.DQ.GetCDO_DO_export_zhangbao1BasicList.Sources.DO_export_zhangbao1.Columns.Name.Text", "Type": 0 } },
        //     { "isShow": true, "ColName": "Creator", "ExcelColName": "创建人", "DataType": "String", "ValueInfo_ColName": { "ShowValue": "Creator", "ReferenceExpr": "Schema.DQ.GetCDO_DO_export_zhangbao1BasicList.Sources.DO_export_zhangbao1.Columns.Creator.Code", "Type": 0 }, "ValueInfo_ExcelColName": { "ShowValue": "创建人", "ReferenceExpr": "Schema.DQ.GetCDO_DO_export_zhangbao1BasicList.Sources.DO_export_zhangbao1.Columns.Creator.Text", "Type": 0 } },
        //     { "isShow": true, "ColName": "CreateTime", "ExcelColName": "创建时间", "DataType": "DateTime", "ValueInfo_ColName": { "ShowValue": "CreateTime", "ReferenceExpr": "Schema.DQ.GetCDO_DO_export_zhangbao1BasicList.Sources.DO_export_zhangbao1.Columns.CreateTime.Code", "Type": 0 }, "ValueInfo_ExcelColName": { "ShowValue": "创建时间", "ReferenceExpr": "Schema.DQ.GetCDO_DO_export_zhangbao1BasicList.Sources.DO_export_zhangbao1.Columns.CreateTime.Text", "Type": 0 } },

        //     { "isShow": false, "ColName": "LastModifierName", "ExcelColName": "最后修改人姓名", "DataType": "String", "ValueInfo_ColName": { "ShowValue": "LastModifierName", "ReferenceExpr": "Schema.DQ.GetCDO_DO_export_zhangbao1BasicList.Sources.DO_export_zhangbao1.Columns.LastModifierName.Code", "Type": 0 }, "ValueInfo_ExcelColName": { "ShowValue": "最后修改人姓名", "ReferenceExpr": "Schema.DQ.GetCDO_DO_export_zhangbao1BasicList.Sources.DO_export_zhangbao1.Columns.LastModifierName.Text", "Type": 0 } },
        //     { "isShow": false, "ColName": "LastModifier", "ExcelColName": "最后修改人", "DataType": "String", "ValueInfo_ColName": { "ShowValue": "LastModifier", "ReferenceExpr": "Schema.DQ.GetCDO_DO_export_zhangbao1BasicList.Sources.DO_export_zhangbao1.Columns.LastModifier.Code", "Type": 0 }, "ValueInfo_ExcelColName": { "ShowValue": "最后修改人", "ReferenceExpr": "Schema.DQ.GetCDO_DO_export_zhangbao1BasicList.Sources.DO_export_zhangbao1.Columns.LastModifier.Text", "Type": 0 } },
        //     { "isShow": false, "ColName": "LastModifyTime", "ExcelColName": "最后修改时间", "DataType": "Timestamp", "ValueInfo_ColName": { "ShowValue": "LastModifyTime", "ReferenceExpr": "Schema.DQ.GetCDO_DO_export_zhangbao1BasicList.Sources.DO_export_zhangbao1.Columns.LastModifyTime.Code", "Type": 0 }, "ValueInfo_ExcelColName": { "ShowValue": "最后修改时间", "ReferenceExpr": "Schema.DQ.GetCDO_DO_export_zhangbao1BasicList.Sources.DO_export_zhangbao1.Columns.LastModifyTime.Text", "Type": 0 } }
        //   ]
        // }
      });

      const exportConfigMore = computed(() => {
        return {
          AdvancedFilter: publicMethod.filterExpression.value,
          AdvancedSort: publicMethod.sortExpression.value,
          FasDynamicFilter: JSON.stringify(publicMethod.fasDynamicFilter.value),
        };
      });
      const isDesktop = computed(() => {
        return !($q.screen.xs || $q.platform.is.mobile);
      });
      const refShowPopupColumnsSetting = ref();
      const refImportExport = ref();
      const renderToolbarWithListView = () => {
        return (
          <div
            class='row q-gutter-xs'
            style='overflow: hidden;justify-content: flex-end;'
          >
            {/* {JSON.stringify(exportConfigMore.value)}eeee
            {JSON.stringify(exportConfig.value)} */}
            <TImportExport
              ref={refImportExport}
              instanceCode={attrs.instanceCode}
              exportConfigMore={exportConfigMore.value}
              importConfig={null}
              exportConfig={exportConfig.value}
              exportFileName={props.exportFileName}
              // @beforeImport="beforeImport"
              // @afterImport="afterImport"
              // :beforeImportJSScript="beforeImportJSScript"
              onBeforeExport={payload => {
                emit('ListExport_BeforeExport', payload);
              }}
              onAfterExport={payload => {
                emit('ListExport_AfterExport', payload);
              }}
              beforeExportJSScript={props.beforeExportJSScript}
              // @beforeExport="beforeExport"
              // @afterExport="afterExport"
              // :beforeExportJSScript="beforeExportJSScript"
            ></TImportExport>
            {props.enableGrouping_GridData && isDesktop.value && (
              <QBtn
                tabindex='1'
                ripple={false}
                class='listView_toolbar_btn'
                style='min-width:auto;'
                icon='fas dx-icon icon-fasquickfilter'
                onClick={dataGridGroupFilterClickHandler}
              />
            )}
            <QBtn
              tabindex='1'
              ripple={false}
              class='listView_toolbar_btn'
              style='min-width:auto;'
              icon='fas icon-t-filter'
              onClick={dataGridFilterClickHandler}
            />
            <QBtn
              ref={refShowPopupColumnsSetting}
              tabindex='1'
              ripple={false}
              class='listView_toolbar_btn'
              style='min-width:auto; margin-right:1px;'
              icon='fas fas-icon icon-t-set-up'
              onClick={event => {
                clickFalg.columnSetting = event instanceof PointerEvent;
                showPopupColumnsSetting.value = !showPopupColumnsSetting.value;
              }}
            />
          </div>
        );
      };

      const btnGroupItemClick = function (params) {
        switch (params.value) {
          case C_TOOLBAR_KEY.lvGroupfilter:
            dataGridGroupFilterClickHandler();
            break;
          case C_TOOLBAR_KEY.lvFilter:
            dataGridFilterClickHandler();
            break;
          case C_TOOLBAR_KEY.lvColumnsetting:
            showPopupColumnsSetting.value = !showPopupColumnsSetting.value;
            break;
          case C_TOOLBAR_KEY.lvExport:
            refImportExport.value?.handleExport2();
            break;
          case C_TOOLBAR_KEY.lvExportlist:
            refImportExport.value?.handleMissionList();
            break;
          default:
            emit('toolbarClick', params);
            emit('listToolbarClick', params);
            break;
        }
      };

      const refListViewToolbarGroup = ref();

      function mappingButtonGroupEvent(emit, emits) {
        return mappingEvent(emit, emits, '_ButtonGroup');
      }

      const lvButGroupEvent = mappingButtonGroupEvent(emit, TBtnGroup.emits);
      const readerToolbarWithListViewButtonGroup = () => {
        let dynamicProps = pickProps(
          mappingProps,
          'lvButGroup',
          '_ButtonGroup',
        );
        if (!dynamicProps.moreBtnLable) {
          dynamicProps.moreBtnLable = $q.lang.mixedView?.button.more;
        }
        return (
          <div
            class='row q-gutter-xs'
            style='overflow: hidden; justify-content: flex-end;'
          >
            {readerButtonGroup(dynamicProps)}
          </div>
        );
      };

      const mapStaticItems = val => {
        const staticItems = val?.map(item => {
          let lvLang = $q.lang.mixedView?.toolbar[item.code];

          let label = lvLang || item.label;
          let hint = lvLang || item.hint;
          if (Funcs && Funcs.GetTerms) {
            label = Funcs.GetTerms(item.ValueInfo_label, label);
            hint = Funcs.GetTerms(item.ValueInfo_hint, hint);
          }
          let r = {
            ...toRefs(item),
            label: ref(label),
            hint: ref(hint),
          };
          if (item.value && C_TOOLBAR_KEY.lvGroupfilter === item.value) {
            r.visible.value = mappingProps.enableGrouping_GridData;
          }
          return r;
        });
        return staticItems;
      };

      const readerButtonGroup = dynamicProps => {
        return (
          <TBtnGroup
            style='justify-content: flex-end;'
            ref={refListViewToolbarGroup}
            {...dynamicProps}
            staticItems={mapStaticItems(dynamicProps.staticItems)}
            // btnDropPop={true}
            onBtnGroupItemClick={btnGroupItemClick}
          />
        );
      };

      const clickFalg = reactive({
        addChart: false,
        columnSetting: false,
      });

      const addChart = () => {
        clickFalg.addChart = event instanceof PointerEvent;
        // chartList.value.push({
        //   ChartName: '按照 问题类别 统计',
        //   ChartType: 'fas-bar-chart',
        //   GroupColumn: 'CreatorName',
        //   Aggregation: 'count',
        //   AggregationFiled: '',
        //   SortType: 'value',
        //   DataSort: '',
        //   AggDateValue: '',
        //   visible: false,
        // });
        configChartInstance.value = {
          ChartName: '',
          ChartType: 'fas-pie-chart',
          GroupColumn: '',
          Aggregation: 'count',
          AggregationFiled: '',
          SortType: 'value',
          DataSort: '1',
          AggDateValue: '',
        };
        chartConfigDialog.value = true;
      };
      const chartConfigDialog = ref(false);
      const configChartInstance = ref();
      const refAddChart = ref();
      watch(
        () => {
          return chartConfigDialog.value;
        },
        val => {
          if (false == val) {
            if (false == clickFalg.addChart) {
              nextTick(() => {
                refAddChart.value?.$el?.focus();
              });
            }
            clickFalg.addChart = false;
          }
        },
      );
      const renderToolbarWithChartView = () => {
        return (
          <div
            class='row items-center'
            style='overflow: hidden; justify-content: flex-end; column-gap: 8px;'
            ref={refChartGrid}
          >
            {chartConfigDialog.value && (
              <ChartConfig
                terms={Terms}
                instance={configChartInstance.value}
                v-model:show={chartConfigDialog.value}
                data={chartRows.value}
                columns={props.optColumns}
                chartList={chartList.value}
                onConfirm={e => {
                  chartList.value.push(e);
                  proxyThis.UpdateAdvQuery('ChartView');
                }}
              ></ChartConfig>
            )}
            <div class='col-auto'>
              <TButton
                ref={refAddChart}
                label={$q.lang.mixedView?.title?.chart}
                icon='fas dx-icon icon-t-plus'
                class='tr-button-default'
                onClick={addChart}
              />
            </div>
            <div class='col-auto'>
              <TButton
                label={$q.lang.mixedView?.title?.refresh}
                icon='fas dx-icon icon-t-refresh'
                class='tr-button-default'
                onClick={() => {
                  queryChart();
                }}
              />
            </div>
            <div class='col-auto'>
              <TSelect
                style='min-width: 50px'
                class='tr-select-noborder select-tabindex vm-chartpage-select'
                tabindex='1'
                borderless
                emit-value
                map-options
                v-model={proxyThis.EnableChartPaging}
                onUpdate:modelValue={() => {
                  queryChart();
                  proxyThis.UpdateAdvQuery('ChartView');
                }}
                options={[
                  { label: $q.lang.mixedView?.title?.pagination, value: 'yes' },
                  {
                    label: $q.lang.mixedView?.title?.nonPagination,
                    value: 'no',
                  },
                ]}
              />
            </div>
          </div>
        );
      };

      const showPopupColumnsSetting = ref(false);
      watch(
        () => {
          return showPopupColumnsSetting.value;
        },
        val => {
          if (false == val) {
            if (false == clickFalg.columnSetting) {
              nextTick(() => {
                refShowPopupColumnsSetting.value?.$el?.focus();
              });
            }
            clickFalg.columnSetting = false;
          }
        },
      );
      const dataGridEvent = mappingDataGridEvent(emit, TDataGrid.emits);
      const renderMainWithListView = () => {
        let dynamicProps = pickDataGridProps(mappingProps);

        return (
          <div>
            {/* {h(TDataGrid, gdProps)} */}
            <div class='del-q-col-gutter-sm' style='padding-top: 5px;'>
              <TDataGrid
                ref={refDataGrid}
                {...dynamicProps}
                {...dataGridEvent}
                menuDataSource={[]}
                // onRequest={(e2) => emit(`request_GridData`, e2)}
                // separator='horizontal'
                showStriped={false}
                v-model:showPopupColumnsSetting={showPopupColumnsSetting.value}
                optColumns={mappingProps.optColumns}
                onUpdateAdvQuery={() => proxyThis.UpdateAdvQuery('data-grid')}
                // disableFixedColumn={true}
                allowColumnResizing={true}
                onUpdateAdvQueryWithUserProfile={
                  OnUpdateAdvQueryWithUserProfile
                }
                onUpdateAdvQueryWithResetSort={OnUpdateAdvQueryWithResetSort}
                onUpdateAdvQueryWithPageSizeChange={
                  OnUpdateAdvQueryWithPageSizeChange
                }
                onGroupChanged={() => {
                  // emit('groupChanged_GridData');
                  // tabsLoadedFlag.ListView = false;
                  tabsLoadedFlag.ChartView = false;
                }}
                onGroupFieldChange={() => {
                  // emit('groupChanged_GridData');
                  // tabsLoadedFlag.ListView = false;
                  tabsLoadedFlag.ChartView = false;
                }}
              ></TDataGrid>
            </div>
          </div>
        );
      };

      const refQuickFilter = ref();

      function pickQuickFilterProps(mappingProps) {
        return pickProps(mappingProps, 'qfBind', '_QuickFilter');
      }

      function mappingQuickFilterEvent(emit, emits) {
        return mappingEvent(emit, emits, '_QuickFilter');
      }

      const quickFilterEvent = mappingQuickFilterEvent(
        emit,
        TQuickFilter.emits,
      );
      const renderQuickFilter = () => {
        let dynamicProps = pickQuickFilterProps(mappingProps);

        return (
          <>
            {/* {JSON.stringify(dynamicProps)} */}
            {/* {JSON.stringify(props.enableQuickFilter)} */}
            {/* {JSON.stringify(props.loading_GridData || props.loading_all)} */}
            {props.enableQuickFilter && (
              <TQuickFilter
                style='margin-bottom:7px;'
                ref={refQuickFilter}
                {...dynamicProps}
                {...quickFilterEvent}
                isPcOnly={true}
                optColumns={props.optColumns}
                loading={props.loading_GridData || props.loading_all}
                onFilterChanged={onFilterChangedHandler}
                // Mock
                // quickItems={quickItems.value}
                // quickItemSummary={quickItemSummary.value}
                // onInit={onInitHandler}
                // onQuerySummary={onQuerySummaryHandler}
                // Mock
              ></TQuickFilter>
            )}
          </>
        );
      };

      const onFilterChangedHandler = () => {
        // publicMethod.query();
        const filterChangedArgs = { cancel: false };
        emit('filterChanged', filterChangedArgs);
        if (filterChangedArgs.cancel) {
          return;
        }
        tabsLoadedFlag.ListView = false;
        tabsLoadedFlag.ChartView = false;
        publicMethod.switchView(tab.value);
      };

      const quickItems = ref({});
      const quickItemSummary = ref({});
      const onInitHandler = () => {
        quickItems.value = _.transform(
          refQuickFilter.value?.filterItemsIsSDO,
          // props.filterFields_QuickFilter,
          // refQuickFilter.value.filterSDOItems(props.filterFields_QuickFilter),
          (result, f) => {
            result[f.fieldAlias] = [
              { label: '状态-0', value: '0' },
              { label: '状态-1', value: '1' },
              { label: '英文-2', value: '2' },
            ];
          },
          {},
        );
      };

      const onQuerySummaryHandler = groupColumn => {
        console.log('onQuerySummaryHandler', groupColumn);
        let mockSummary = refQuickFilter.value.mockSummary;
        quickItemSummary.value = refQuickFilter.value.wrapSummary([
          { Total: mockSummary(), State: '0', State2: '0' },
          { Total: mockSummary(), State: '1', State2: '2' },
          { Total: mockSummary(), State: '2', State2: 'CN' },
          { Total: mockSummary(), State: 'CN', State2: 'CN' },
          { Total: mockSummary(), State: 'EN', State2: 'EN' },
          { Total: mockSummary(), State: 'EN', State2: 'EN' },
        ]);
      };

      let chartList = ref([
        // {
        //   ChartName: '按照 问题类别 统计',
        //   ChartType: 'fas-bar-chart',
        //   GroupColumn: 'CreatorName',
        //   Aggregation: 'count',
        //   AggregationFiled: '',
        //   SortType: 'value',
        //   DataSort: '',
        //   AggDateValue: '',
        //   visible: false,
        // },
        // {
        //   ChartName: '按照 问题类别2 统计',
        //   ChartType: 'fas-line-chart',
        //   GroupColumn: 'CreatorName',
        //   Aggregation: 'count',
        //   AggregationFiled: '',
        //   SortType: 'value',
        //   DataSort: '',
        //   AggDateValue: '',
        //   visible: false,
        // },
        // {
        //   ChartName: '按照 问题类别2 统计',
        //   ChartType: 'fas-pie-chart',
        //   GroupColumn: 'CreatorName',
        //   Aggregation: 'count',
        //   AggregationFiled: '',
        //   SortType: 'value',
        //   DataSort: '',
        //   AggDateValue: '',
        //   visible: false,
        // },
      ]);

      const isFullChart = ref(false);
      const computedChartViewMinHeight = computed(() => {
        if ('dynamic' === mappingProps.fillMode_GridData) {
          return isFullChart.value ? mappingProps.chartFullHeight : 'unset';
        } else {
          return refDataGrid.value.height;
        }
      });

      const renderMainWithChartView = () => {
        return (
          <ChartView
            terms={Terms}
            ref={refChartGrid}
            columns={props.optColumns}
            v-model:chartList={chartList.value}
            data={chartRows.value}
            loading={props.loading_all}
            onUpdateAdvQuery={() => proxyThis.UpdateAdvQuery('ChartView')}
            onAddchart={addChart}
            chartFullHeight={
              'dynamic' === mappingProps.fillMode_GridData
                ? mappingProps.chartFullHeight
                : false
            }
            onFullChart={isFull => {
              isFullChart.value = isFull;
            }}
          />
        );
      };

      return () => {
        return (
          <div class='t-mixed-view' v-removeTabindex>
            <div class='row items-center t-mixed-view_tabs-toolbar'>
              <div
                class={[
                  'col-auto col-sm-auto col-xs-12 t-mixed-view_tabs',
                  tabs.value.length === 1 ? 't-single-tab' : '',
                ]}
              >
                {renderTabs()}
              </div>
              <div class='col col-sm col-xs-12'>
                <QTabPanels
                  v-model={tab.value}
                  style='background-color:transparent;'
                >
                  <QTabPanel name='ListView' class='q-pa-none'>
                    {mappingProps.listViewToolbarButtonGroups ? (
                      <>
                        <div style='display:none'>
                          {renderToolbarWithListView()}
                        </div>
                        {readerToolbarWithListViewButtonGroup()}
                      </>
                    ) : (
                      renderToolbarWithListView()
                    )}
                  </QTabPanel>
                  <QTabPanel name='ChartView' class='q-pa-none'>
                    {renderToolbarWithChartView()}
                  </QTabPanel>
                </QTabPanels>
              </div>
            </div>
            <div class='row'>
              <div class='col-12'>
                {/* <div>rows_GridData={props.rows_GridData.length}</div>
                <div>rows_all={props.rows_all.length}</div>
                <div>chartRows.value={chartRows.value.length}</div> */}
                <QTabPanels v-model={tab.value} keep-alive>
                  <QTabPanel name='ListView' class='q-pa-none'>
                    {renderQuickFilter()}
                    {renderMainWithListView()}
                  </QTabPanel>
                  <QTabPanel
                    name='ChartView'
                    class='q-pa-none'
                    style={
                      refDataGrid.value
                        ? {
                            marginBottom: '10px',
                            minHeight: computedChartViewMinHeight.value,
                          }
                        : { marginBottom: '10px' }
                    }
                  >
                    {/* <div>
                      <div>chartRows={chartRows?.value?.length}</div>
                      <div>rows_all={props.rows_all.length}</div>
                      <div>rows={props.rows_GridData.length}</div>
                    </div> */}
                    {/* <div>chartList.value:{chartList.value.length}</div> */}
                    {'ChartView' == tab.value && renderMainWithChartView()}
                    {/* {renderMainWithChartView()} */}
                  </QTabPanel>
                </QTabPanels>
              </div>
            </div>
          </div>
        );
      };
    } catch (e) {
      const errorLog = window['console'];
      errorLog.group('mixins_mixedView.setup.errorLog');
      errorLog.log(e);
      errorLog.groupEnd();
    }
  },
});
